import { createPage } from '@mpxjs/core'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore 图片
import transparentPic from '../../assets/snap/透明层.png'
import { CDN_HOST } from '../../config'
import { saveFile, shareFile } from '../../utils'

createPage({
  data: {
    position: 'front',
    path: '',
    isDown: false,
    edgeLength: 0,
    cityPic: '',
    petalPic: '',
    isLoading: false,
    resetShow: false,
    isSave: false,
    isShowMask: true
  },
  onLoad({ city }) {
    if (!city) city = '上海'
    // wx.createSelectorQuery()
    //   .select('#camera')
    //   .boundingClientRect((rect) => {
    //     const min = Math.min(rect.width, rect.height)
    //     this.setData({
    //       edgeLength: min
    //     })
    //   })
    //   .exec()
    this.ctx = wx.createCameraContext()
    wx.showLoading({
      title: '下载资源中'
    })
    wx.cloud
      .downloadFile({
        fileID: `${CDN_HOST}/city/${city}.png`
      })
      .then((res) => {
        if (this.petalPic) {
          wx.hideLoading()
        }
        this.setData({
          cityPic: res.tempFilePath
        })
        // wx.getImageInfo({
        //   src: res.tempFilePath
        // }).then(console.log)
      })
    wx.cloud
      .downloadFile({
        fileID: `${CDN_HOST}/petal/${city}.png`
      })
      .then((res) => {
        if (this.cityPic) wx.hideLoading()
        this.setData({
          petalPic: res.tempFilePath
        })
        wx.getImageInfo({
          src: res.tempFilePath
        }).then((res) => {
          this.setData({
            edgeLength: res.width
          })
        })
      })

    wx.getStorage({ key: 'isShowSnapMask' })
      .then(() => {
        this.setData({
          isShowMask: false
        })
      })
      .catch(() => {
        this.setData({
          isShowMask: true
        })
        wx.setStorage({
          key: 'isShowSnapMask',
          data: true
        })
      })
  },
  methods: {
    takePhoto() {
      if (this.cityPic && this.petalPic) {
        this.ctx.takePhoto({
          quality: 'high',
          success: (res) => {
            this.setData({
              path: res.tempImagePath,
              isLoading: true
            })
            wx.showLoading({
              title: '生成中'
            })
            this.createPic()
          }
        })
      }
    },
    choosePic() {
      if (this.cityPic && this.petalPic) {
        wx.chooseMedia({
          count: 1,
          mediaType: ['image'],
          sourceType: ['album'],
          sizeType: ['compressed']
        }).then((res) => {
          this.setData({
            path: res.tempFiles[0].tempFilePath
          })
          this.createPic()
        })
      }
    },
    onReverse() {
      this.setData({
        position: this.position === 'front' ? 'back' : 'front'
      })
    },
    createPic() {
      const query = wx.createSelectorQuery()
      query
        .selectAll('#sourceCanvas, #targetCanvas')
        .fields({ node: true, size: true })
        .exec((res) => {
          this.targetCanvas = res[0][1].node
          this.createBg(res[0][1])
            .then(() => this.createAvatar(res[0][0]))
            .then(() => {
              this.setData({
                isLoading: false
              })
              wx.hideLoading()
            })
          // .then(() => {
          //   wx.enableAlertBeforeUnload({
          //     message: '点击返回您的专属AR照片将不会保存，请确认是否保存？'
          //   })
          // })
        })
    },
    createAvatar(res) {
      const canvas = res.node
      const ctx = canvas.getContext('2d')
      const dpr = wx.getWindowInfo().pixelRatio
      canvas.width = res.width * dpr
      canvas.height = res.height * dpr
      ctx.clearRect(0, 0, canvas.width, canvas.height)

      // 创建一个新的图片对象

      return new Promise((resolve) => {
        const avatarImg = canvas.createImage()
        avatarImg.src = this.path // 替换为你的图片 URL
        avatarImg.onload = () => {
          // 定义圆形的中心点和半径
          ctx.clearRect(0, 0, canvas.width, canvas.height)

          // // 定义圆形的中心点和半径
          const centerX = canvas.width / 2
          const centerY = canvas.height / 2
          // // 计算缩放比例
          const scale =
            Math.max(
              canvas.width / avatarImg.width,
              canvas.height / avatarImg.height
            ) * 0.46
          // 计算图片绘制的尺寸和位置
          const imgWidth = avatarImg.width * scale
          const imgHeight = avatarImg.height * scale
          const radius = Math.min(imgWidth, imgHeight) / 2
          const imgX = (canvas.width - imgWidth) / 2
          const imgY = (canvas.height - imgHeight) / 2

          // // 在 sourceCanvas 上绘制图像
          ctx.drawImage(avatarImg, imgX, imgY, imgWidth, imgHeight)

          // 获取图像数据并应用圆形剪辑
          const avatarImageData = ctx.getImageData(
            0,
            0,
            canvas.width,
            canvas.height
          )
          // const data = imageData.data
          // for (let y = 0; y < canvas.height; y++) {
          //   for (let x = 0; x < canvas.width; x++) {
          //     const index = (y * canvas.width + x) * 4
          //     const dx = x - centerX
          //     const dy = y - centerY
          //     if (dx * dx + dy * dy > radius * radius) {
          //       data[index + 3] = 0 // 设置 alpha 通道为 0，使其透明
          //     }
          //   }
          // }

          // ctx.putImageData(imageData, 0, 0)

          const petalImg = canvas.createImage()
          petalImg.src = this.petalPic
          petalImg.onload = () => {
            // const avatarImgRe = canvas.toDataURL()
            ctx.clearRect(0, 0, canvas.width, canvas.height)
            ctx.drawImage(
              petalImg,
              0,
              0,
              petalImg.width * dpr,
              petalImg.height * dpr
            )
            const petalImageData = ctx.getImageData(
              0,
              0,
              canvas.width,
              canvas.height
            )
            const avatarData = avatarImageData.data
            const petalData = petalImageData.data
            for (let y = 0; y < canvas.height; y++) {
              for (let x = 0; x < canvas.width; x++) {
                const index = (y * canvas.width + x) * 4
                const dx = x - centerX
                const dy = y - centerY
                if (dx * dx + dy * dy > radius * radius) {
                  avatarData[index] = petalData[index] // 设置 alpha 通道为 0，使其透明
                  avatarData[index + 1] = petalData[index + 1] // 设置 alpha 通道为 0，使其透明
                  avatarData[index + 2] = petalData[index + 2] // 设置 alpha 通道为 0，使其透明
                  avatarData[index + 3] = petalData[index + 3] // 设置 alpha 通道为 0，使其透明
                }
              }
            }
            ctx.putImageData(avatarImageData, 0, 0)
            const targetAvatar = canvas.createImage()
            targetAvatar.src = canvas.toDataURL()
            targetAvatar.onload = () => {
              const { pixelRatio: dpr } = wx.getWindowInfo()
              const targetCtx = this.targetCanvas.getContext('2d')
              const getLength = (num) =>
                (num * this.targetCanvas.width) / dpr / 283

              const targetRadius = getLength(96) * dpr
              const x = getLength(0)
              const y = getLength(65)
              const targetX = this.targetCanvas.width - targetRadius - x * dpr
              const targetY =
                this.targetCanvas.height - targetRadius - y * dpr - 3
              targetCtx.drawImage(
                targetAvatar,
                0,
                0,
                targetAvatar.width,
                targetAvatar.height,
                targetX,
                targetY,
                targetRadius,
                targetRadius
              )
              resolve(true)
            }
          }
        }
      })

      // 等待图片加载完成
    },
    createBg(res) {
      const canvas = res.node

      const { pixelRatio: dpr } = wx.getWindowInfo()
      canvas.width = res.width * dpr
      canvas.height = res.height * dpr

      return this.drawImage(canvas, this.cityPic, 'bg').then(() =>
        this.drawImage(canvas, transparentPic, 'transparent')
      )
    },
    drawImage(canvas, src, type) {
      return new Promise((resolve) => {
        const img = canvas.createImage()
        const ctx = canvas.getContext('2d')
        img.src = src // 替换为你的图片 URL
        // 等待图片加载完成
        img.onload = function () {
          if (type === 'bg') {
            // 白边bug
            const scale = Math.max(
              canvas.width / img.width,
              canvas.height / img.height
            )
            // 计算图片绘制的尺寸和位置
            const imgWidth = img.width * scale
            const imgHeight = img.height * scale
            ctx.drawImage(img, 0, 0, imgWidth, imgHeight)
          } else {
            const scale = Math.min(
              canvas.width / img.width,
              canvas.height / img.height
            )
            // 计算图片绘制的尺寸和位置
            const imgWidth = img.width * scale
            const imgHeight = img.height * scale
            ctx.drawImage(
              img,
              0,
              0,
              img.width,
              img.height,
              0,
              canvas.height - imgHeight,
              imgWidth,
              imgHeight
            )
          }
          resolve(canvas)
        }
      })
    },
    onReset() {
      if (this.isSave) {
        this.setData({
          path: ''
        })
      } else {
        this.setData({
          // path: ''
          resetShow: true
        })
      }
      // wx.disableAlertBeforeUnload()
    },
    onSave() {
      const imgSrc = this.targetCanvas.toDataURL()
      saveFile(imgSrc)
      this.setData({
        isSave: true,
        path: ''
      })
    },
    onShare() {
      const imgSrc = this.targetCanvas.toDataURL()
      shareFile(imgSrc)
    },
    onResetCancel() {
      this.setData({
        resetShow: false,
        path: ''
      })
    },
    onResetSave() {
      this.setData({
        resetShow: false
      })
      this.onSave()
    },
    onCloseMask() {
      this.setData({
        isShowMask: false
      })
    }
  }
})
